import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

import { reqController } from './config';

@Injectable()
export class FanService {
    constructor(private http: Http) { }

    // 同步接口
    synchronize(): Promise<any> {
        return this.http.get(reqController.synchronization)
            .toPromise()
            .then(res => res.json())
            .catch(this.handleError);
    };

    // 获取粉丝列表
    list(pagenum: string, pagesize: string, search: string): Promise<any> {
        let params: URLSearchParams = new URLSearchParams();
        params.set('pagenum', pagenum);
        params.set('pagesize', pagesize);
        params.set('search', search);
        
        return this.http.get(reqController.fanPort, { search: params })
            .toPromise()
            .then(res => res.json())
            .catch(this.handleError);
    };

    // 处理请求出错
    handleError(error: any): Promise<any> {
        alert('程序请求出错');
        return Promise.reject(error.message || error);
    };
}